package com.appspot.aliga.service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;

import com.appspot.aliga.Gameday;
import com.appspot.aliga.LeagueTableEntry;
import com.appspot.aliga.Match;

public class ALigaService {
	
	private static GamedayComparator GAMEDAY_COMP = new GamedayComparator();
	private static LeagueTableEntryComperator LEAGUE_COMP = new LeagueTableEntryComperator();
	private static MatchComparator MATCH_COMP = new MatchComparator();
	
	private ALigaDBAdapter dbApdapter;
	
	public ALigaService(Context ctx) {
		this.dbApdapter = new ALigaDBAdapter(ctx);
		this.dbApdapter.open();
	}
	
	public List<Gameday> getGameDays(int leagueID){
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL("http://a-liga.appspot.com/service?method=getGamedays&leagueID=" + leagueID);
			urlConnection = (HttpURLConnection) url.openConnection();

			InputStream in = new BufferedInputStream(
					urlConnection.getInputStream());
			String json = readStream(in);
			JSONArray ja = (JSONArray) new JSONTokener(json).nextValue();
			
			List<Gameday> gds = new ArrayList<Gameday>();
			for (int i = 0; i < ja.length(); i++) {
				JSONObject gameday = (JSONObject) ja.get(i);
				Gameday gd = Gameday.fromJSON(gameday);
				gds.add(gd);
			}
			Collections.sort(gds, GAMEDAY_COMP);
			return gds;
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			urlConnection.disconnect();
		}
		return Collections.emptyList();
	}
	
	public List<Match> getMatches(int leagueID, int gameday){
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL("http://a-liga.appspot.com/service?method=getMatches&leagueID=" + leagueID + "&gameday=" + gameday);
			urlConnection = (HttpURLConnection) url.openConnection();

			InputStream in = new BufferedInputStream(
					urlConnection.getInputStream());
			String json = readStream(in);
			JSONArray ja = (JSONArray) new JSONTokener(json).nextValue();
			
			List<Match> matches = new ArrayList<Match>();
			for (int i = 0; i < ja.length(); i++) {
				JSONObject match = (JSONObject) ja.get(i);
				Match m = Match.fromJSON(match);
				matches.add(m);
			}
			Collections.sort(matches, MATCH_COMP);
			return matches;
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			urlConnection.disconnect();
		}
		return Collections.emptyList();
	}
	
	public List<LeagueTableEntry> getLeagueTable(int leagueID){
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL("http://a-liga.appspot.com/service?method=getLeagueTable&leagueID=" + leagueID);
			urlConnection = (HttpURLConnection) url.openConnection();

			InputStream in = new BufferedInputStream(
					urlConnection.getInputStream());
			String json = readStream(in);
			JSONArray ja = (JSONArray) new JSONTokener(json).nextValue();
			
			List<LeagueTableEntry> entries = new ArrayList<LeagueTableEntry>();
			for (int i = 0; i < ja.length(); i++) {
				JSONObject entry = (JSONObject) ja.get(i);
				LeagueTableEntry leagueTableEntry = LeagueTableEntry.fromJSON(entry);
				entries.add(leagueTableEntry);
			}
			Collections.sort(entries, LEAGUE_COMP);
			return entries;
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			urlConnection.disconnect();
		}
		return Collections.emptyList();
	}
	
	private String readStream(InputStream in) throws IOException {
		 Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(in, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            in.close();
        }
        return writer.toString();
	}
}
